<script setup>
import {useUserStore} from '@/stores/user'
import {useRouter, useRoute} from 'vue-router'
import {computed, nextTick, ref} from 'vue'
import * as echarts from 'echarts';
import { getSignInCalendar, signInAPI } from '@/api/Multifunction.js';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import {ElMessage} from "element-plus";
import {DArrowLeft, DArrowRight, Edit} from "@element-plus/icons-vue";

const userStore = useUserStore()
const router = useRouter()
const route = useRoute()
const userId = useUserStore().UserId;
const showCalendar = ref(false);
const currentMonth = ref(dayjs()); // 当前展示的月份

// 计算属性获取当前路由路径
const activeIndex = computed(() => route.path)

function handleSelect(index) {
  router.push(index)
}

function logout() {
  userStore.logout()
}

// 跳转到个人信息页面的函数
function goToMyInfo() {
  router.push({path: '/myInfo'});
}
const toggleCalendar = async () => {
  showCalendar.value = !showCalendar.value;
  console.log("Toggle Calendar:", showCalendar.value); // 确认是否触发
  if (showCalendar.value) {
    await nextTick();
    await renderCalendarChart();
  }
};


// 关闭弹窗
const closeDialog = () => {
  showCalendar.value = false;
};

// 当前月份的格式化展示
const formattedMonth = computed(() => currentMonth.value.format('YYYY年MM月'));

// 切换月份
const prevMonth = () => {
  currentMonth.value = currentMonth.value.subtract(1, 'month');
  renderCalendarChart();
};

const nextMonth = () => {
  currentMonth.value = currentMonth.value.add(1, 'month');
  renderCalendarChart();
};

// 签到功能
const signIn = async () => {
  const response = await signInAPI(userId);
  if (response.data.code === 200) {
    await renderCalendarChart();
    ElMessage.success('签到成功');
    closeDialog(); // 确认签到后关闭弹窗
  } else {
    ElMessage.error(response.data.msg);
  }
};

const renderCalendarChart = async () => {
  const calendarDom = document.getElementById('calendarChart');
  if (!calendarDom) return;

  const chart = echarts.init(calendarDom);

  const response = await getSignInCalendar(userId);
  const signInDates = response.data.data;

  const monthStart = currentMonth.value.startOf('month').format('YYYY-MM-DD');
  const monthEnd = currentMonth.value.endOf('month').format('YYYY-MM-DD');

  const option = {
    title: {
      left: 'center',
      top: '5%',
      textStyle: {
        color: '#2e7d32', // 深绿色标题
        fontSize: 20,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      position: 'top',
      formatter: (params) => `${params.value[0]}: 已签到`
    },
    visualMap: {
      show: false,
      min: 0,
      max: 1,
      inRange: {
        color: ['#e8f5e9', '#43a047'] // 从浅绿色到深绿色的渐变
      }
    },
    calendar: {
      orient: 'vertical', // 垂直方向排列
      range: [monthStart, monthEnd],
      cellSize: ['auto', 30],
      itemStyle: {
        borderWidth: 1,
        borderColor: '#ddd',
        shadowBlur: 5,
        shadowColor: 'rgba(0, 0, 0, 0.1)',
        color: '#e8f5e9', // 背景浅绿色
        borderRadius: 6 // 方块圆角
      },
      splitLine: {
        lineStyle: {
          color: '#ddd',
          type: 'dotted'
        }
      },
      dayLabel: {
        color: '#333'
      },
      monthLabel: {
        show: false
      }
    },
    series: {
      type: 'heatmap',
      coordinateSystem: 'calendar',
      data: Array.from({ length: currentMonth.value.daysInMonth() }, (_, i) => {
        const date = currentMonth.value.date(i + 1).format('YYYY-MM-DD');
        return [date, signInDates.includes(date) ? 1 : 0];
      }),
      label: {
        show: true,
        formatter: (params) => dayjs(params.value[0]).date(), // 显示日期数字
        color: '#2e7d32'
      },
      itemStyle: {
        borderColor: '#fff',
        borderWidth: 1,
        color: '#43a047', // 已签到颜色为深绿色
        shadowBlur: 10,
        shadowColor: 'rgba(67, 160, 71, 0.5)', // 阴影效果
      },
      emphasis: {
        itemStyle: {
          color: '#66bb6a' // 悬停时更浅的绿色
        }
      }
    },
    animationEasing: 'quarticOut',
    animationDuration: 1200
  };

  chart.setOption(option);
};

</script>

<template>
  <div style="margin-top: -24%; width:100%; margin-left: -49%; position:absolute;">
    <img src="@/assets/Photo/img.png" style="width: 100%;height: 187px " alt=""/>

    <el-menu
        :default-active="activeIndex"
        mode="horizontal"
        background-color="#228d26"
        text-color="#ffffff"
        active-text-color="#ffd04b"
        @select="handleSelect"
    >
      <router-link to="/layout/news">
        <el-menu-item class="menu-text" index="/layout/news" >新闻政要</el-menu-item>
      </router-link>
      <router-link to="/layout/data">
        <el-menu-item class="menu-text" index="/layout/data">数据中心</el-menu-item>
      </router-link>
      <router-link to="/layout/second">
        <el-menu-item class="menu-text" index="/layout/second">二手商品</el-menu-item>
      </router-link>
      <router-link to="/layout/green">
        <el-menu-item class="menu-text" index="/layout/green">环保产品</el-menu-item>
      </router-link>
      <router-link to="/layout/carbon">
        <el-menu-item class="menu-text" index="/layout/carbon">碳足迹</el-menu-item>
      </router-link>
<!--      <router-link to="/layout/volunteer">-->
<!--        <el-menu-item class="menu-text" index="/layout/volunteer">志愿活动</el-menu-item>-->
<!--      </router-link>-->
      <router-link to="/layout/message">
        <el-menu-item class="menu-text" index="/layout/message">消息</el-menu-item>
      </router-link>
      <router-link to="/layout/cart">
        <el-menu-item class="menu-text" index="/layout/cart">购物车</el-menu-item>
      </router-link>
      
<!--      签到-->
      <el-menu-item  style="position: absolute;right: 0;margin-right: 150px;margin-top: 0%">
        <img @click="toggleCalendar" style="width: 40px;height: 40px;margin-right: 10px;margin-top: 5px" src="@/assets/Photo/签到.png" alt="">
      </el-menu-item>

      <!-- 个人中心和头像部分 -->
      <el-dropdown style="right: 0;position: absolute;margin-right: 40px;margin-top: 1%">
        <span class="el-dropdown-link" @click="goToMyInfo">
          <img style="margin-left: 40px;" v-if="userStore.avatar" :src="userStore.avatar" alt="头像" class="avatar"/>
          <img v-else src="@/assets/Photo/头像.png" alt="Avatar" class="avatar"/>
          <span class="menu-text">{{ userStore.nickname ? userStore.nickname : '用户' }}</span>
        </span>
        <template #dropdown>
          <el-card shadow="always" class="dropdown-card horizontal-layout">
            <img :src="userStore.avatar" alt="Avatar" class="avatar-large"/>
            <span class="username">{{ userStore.nickname ? userStore.nickname : '用户' }}</span>
            <el-button style="right: -50%;top: -35px;position:relative" type="primary" @click="logout">退出</el-button>
          </el-card>
        </template>
      </el-dropdown>
    </el-menu>

    <!-- 显示子路由内容 -->
    <router-view/>
  </div>

  <!-- 弹窗 -->
  <el-dialog title="签到日历" v-model="showCalendar" width="600px;height: 500px;" @close="closeDialog">
    <div style="display: flex; justify-content: space-between; align-items: center;">
      <el-button icon="el-icon-arrow-left" @click="prevMonth"> <el-icon color="green" size="20px"><DArrowLeft /></el-icon></el-button>
      <span style="font-size: 18px; font-weight: bold;">{{ formattedMonth }}</span>
      <el-button icon="el-icon-arrow-right" @click="nextMonth"> <el-icon color="green" size="20px"><DArrowRight /></el-icon>  </el-button>
    </div>
    <div id="calendarChart" style="width: 100%; height: 400px; margin-top: 20px;"></div>

    <div style="text-align: right; margin-top: 20px;">
      <el-button type="primary" @click="signIn">确认签到</el-button>
    </div>
  </el-dialog>
</template>

<style scoped>
.menu-text {
  font-weight: bold;
  font-size: 18px;
  color: #ffffff;
}

.avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  margin-right: 8px;
}

.avatar-large {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  display: block;
  margin: 0 auto;
}

.dropdown-card {
  width: 300px;
  text-align: center;
  padding: 10px;
  height: 110px;
}

.username {
  font-size: 16px;
  margin-left: 60px;
}

.horizontal-layout {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
}

.el-dropdown-link {
  display: flex;
  align-items: center;
  cursor: pointer;
}
</style>
